/*
 * @Author: CodeHare
 * @Date: 2023-09-06 08:44:11
 * @LastEditors: YangJianFei
 * @LastEditTime: 2024-08-27 09:18:07
 * @Description: 用户管理页面
 */
// ignore_for_file: unnecessary_overrides

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/pages/mine/user_manage/models/user_manager_model.dart';
import 'package:yt_devops/pages/mine/user_manage/user_manage_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/auth/auth_services.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/func_utils.dart';

class UserManageController extends GetxController
    with GetTickerProviderStateMixin {
  final _authServices = Get.put(AuthServices());
  String searchString = '';

  /// 系统管理员列表
  List<dynamic> systemList = [];
  // /// 安装商列表
  // List<dynamic> installerList = [];
  // /// 业主列表
  // List<dynamic> ownerList = [];
  final GlobalKey listKey = GlobalKey();

  /// 站点列表服务
  SiteServices siteServices = Get.put(SiteServices());
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  int currentPage = 1;
  int pageSize = 20;

  // final TextEditingController searchController = TextEditingController();
  String searchName = '';
  double popHeight = 150;
  double scrollControllerOffset = 0;
  ScrollController scrollController = ScrollController();
  bool isShowPop = false;
  int selectedIndex = 0;
  UserManagerModel selectModel = UserManagerModel();
  var organizationId = '';
  List orgTypes = [0];
  var orgId = '';
  var selectedID = ''; //选中的组织id,用户下次进入选择组织页面的回显
  bool isLoading = false; //是否请求过数据,如果请求且为空则显示空
  List allTabs = [
    {
      'label': ResKey.systemAdministrator.tr,
      'type': 0,
      'edit': false,
      'resetSecret': false,
      'disable': false,
      'auth': PermissionConstant.mineUserManageSystemAdd,
    },
    {
      'label': ResKey.installManu.tr,
      'type': 1,
      'edit': false,
      'resetSecret': false,
      'disable': false,
      'auth': PermissionConstant.mineUserManageInstallAdd,
    },
    {
      'label': ResKey.mineUserManagerUserOwner.tr,
      'type': 2,
      'edit': false,
      'resetSecret': false,
      'disable': false,
      'auth': PermissionConstant.mineUserManageOwnerAdd,
    },
  ];
  List tabs = [];
  bool? isTabPage = false; //是否是tab页面 是的话没有返回 显示中间tab
  TabController? tabController;
  Map<String, Object> nowTab = {};

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onInit() {
    getTabsAndAuth();
    // //监听滚动事件，打印滚动位置
    scrollController.addListener(() {
      // print('scrollController.offset=='  + scrollController.offset.toString()); //打印滚动位置
      scrollControllerOffset = scrollController.offset;
      // update();
    });
    tabController = TabController(length: tabs.length, vsync: this);

    tabController!.addListener(() {
      if (tabController!.index == tabController!.animation!.value) {
        nowTab = tabs[tabController!.index];
        if (nowTab['type'] == 0) {
          orgTypes = [0];
          organizationId = '';
          selectedID = '';
          orgId = '';
        } else if (nowTab['type'] == 1) {
          orgTypes = [1, 2, 3];
          organizationId = '';
          selectedID = '';
          orgId = '';
        } else if (nowTab['type'] == 2) {
          orgTypes = [3];
          organizationId = '';
          selectedID = '';
          orgId = '';
        }
        getUserList();
      }
    });
    getUserList();
    super.onInit();
  }

  ///添加用户
  void addUser() {
    Get.toNamed(RouterPath.mineUserManagerAddUser, arguments: {
      'type': nowTab['type'] == 2 ? 3 : nowTab['type'],
    });
  }

  ///选择选择组织机构
  void chooseOrganization() {
    Get.toNamed(RouterPath.mineChooseOrganization, arguments: {
      'selectedID': [selectedID],
      'type': nowTab['type'] == 2 ? 3 : nowTab['type'],
    });
  }

  ///获取拿到的id重新请求数据
  void getOrganizationId(String id) {
    if (id.isNotEmpty) {
      selectedID = id;
      orgId = id;
      organizationId = '';
      List<String> list = id.split('-');
      if (list.isNotEmpty && list.length == 2) {
        orgId = list.last;
        organizationId = '';
      } else if (list.isNotEmpty && list.length == 3) {
        orgId = list[1];
        organizationId = list.last;
      }
    }
    getUserList();
  }

  ///新增用户返回清空组织id,不然可能无法显示刚刚添加的用户
  void addUserRefreshList() {
      if (nowTab['type'] == 0) {
        orgTypes = [0];
        organizationId = '';
        selectedID = '';
        orgId = '';
      } else if (nowTab['type'] == 1) {
        orgTypes = [1, 2, 3];
        organizationId = '';
        selectedID = '';
        orgId = '';
      } else if (nowTab['type'] == 2) {
        orgTypes = [3];
        organizationId = '';
        selectedID = '';
        orgId = '';
      }
    Log.d('orgId==' + orgId.toString());
    getUserList();
  }

  ///获取用户列表
  Future<void> getUserList() async {
    var param = {
      'current': currentPage,
      'pageSize': pageSize,
      'nickName': searchString,
      'orgId': orgId,
      'orgTypes': orgTypes,
      'siteId': organizationId
    };
    if (!isLoading) showLoading(toast: ResKey.loading.tr);
    // if(!isLoading) EasyLoading.show(status:'', maskType: EasyLoadingMaskType.clear);
    var result =
        await _authServices.getUserManagerList(param, onError: (error) {
      dismissLoading();
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      handleException(error);
      return false;
    });
    dismissLoading();
    isLoading = true;
    refreshController.loadComplete();
    refreshController.refreshCompleted();
    if (result != null) {
      var list = result['list'] ?? [];
      List<dynamic> tempList = [];
      list.forEach((item) => tempList.add(UserManagerModel.fromJson(item)));
      if (currentPage == 1) {
        systemList.clear();
      }
      systemList.addAll(tempList);
      if (result['total'] != null && result['total'] <= systemList.length) {
        refreshController.loadNoData();
      }

      update();
    }
  }

  ///去用户详情
  void goToUserDetail(UserManagerModel model) {
    if (isShowPop == false) {
      Get.toNamed(RouterPath.mineUserManagerGotoUserDetail, arguments: {
        'model': model,
        'type': nowTab['type'] == 2 ? 3 : nowTab['type'],
        'editAuth': nowTab['edit'],
      });
    } else {
      isShowPop = false;
      update();
    }
  }

  ///刷新
  void onRefresh() async {
    Log.d('onRefresh==');

    currentPage = 1;
    getUserList();
  }

  ///加载更多
  void onLoading() async {
    currentPage++;
    getUserList();
  }

  ///重置密码
  void restPwd() {
    isShowPop = false;
    update();
    Get.toNamed(RouterPath.mineUserManagerResetPwd,
        arguments: selectModel.userId);
  }

  ///禁用
  void stopUsed() {
    isShowPop = false;
    update();
    if (selectModel.status != null && selectModel.status == '0') {
      BrnDialogManager.showConfirmDialog(
        Get.context!,
        cancel: ResKey.cancel.tr,
        confirm: ResKey.sure.tr,
        title: ResKey.mineUserManagerForbiddenUser.tr,
        onCancel: () => Get.back(),
        onConfirm: () {
          Log.d('发送网络请求关闭页面');
          changeUserStatus(selectModel.userId ?? 0, 1);
          Get.back();
        },
      );
    } else {
      changeUserStatus(selectModel.userId ?? 0, 0);
    }
  }

  ///修改用户状态,禁用 启用
  changeUserStatus(num userId, num index) async {
    var param = {
      'userId': userId,
      'status': index,
    };
    showLoading(toast: ResKey.loading.tr);
    var result = await _authServices.changeUserStatus(param, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    // if(result != null){
    onRefresh();
    // }
  }

  ///设置弹窗的高度
  void setPopHeight(double localPositionY, double height) {
    if (isShowPop == true) {
      isShowPop = false;
      update();
    } else {
      popHeight = height;
      if (localPositionY < 20) {
        popHeight = height + 20;
      }
      if (ScreenUtil().screenHeight - height < 96) {
        scrollController.jumpTo(
            scrollControllerOffset + 96 - (ScreenUtil().screenHeight - height));
        // 延迟执行的代码
        popHeight = ScreenUtil().screenHeight - 96 + 10;
        isShowPop = true;
        update();
        // });
      } else {
        isShowPop = true;
        update();
      }
    }
  }

  ///隐藏弹窗
  hiddenPop() {
    isShowPop = false;
    update();
  }

  getTabsAndAuth() {
    tabs.clear();
    List result = [];
    if (FuncUtils.isPassAuthority([PermissionConstant.mineUserManageSystem])) {
      allTabs[0]['edit'] = FuncUtils.isPassAuthority(
          [PermissionConstant.mineUserManageSystemEdit]);
      allTabs[0]['resetSecret'] = FuncUtils.isPassAuthority(
          [PermissionConstant.mineUserManageSystemResetSecret]);
      allTabs[0]['disable'] = FuncUtils.isPassAuthority(
          [PermissionConstant.mineUserManageSystemDisable]);
      result.add(allTabs[0]);
    }
    if (FuncUtils.isPassAuthority([PermissionConstant.mineUserManageInstall])) {
      allTabs[1]['edit'] = FuncUtils.isPassAuthority(
          [PermissionConstant.mineUserManageInstallEdit]);
      allTabs[1]['resetSecret'] = FuncUtils.isPassAuthority(
          [PermissionConstant.mineUserManageInstallResetSecret]);
      allTabs[1]['disable'] = FuncUtils.isPassAuthority(
          [PermissionConstant.mineUserManageInstallDisable]);
      result.add(allTabs[1]);
    }
    if (FuncUtils.isPassAuthority([PermissionConstant.mineUserManageOwner])) {
      allTabs[2]['edit'] = FuncUtils.isPassAuthority(
          [PermissionConstant.mineUserManageOwnerEdit]);
      allTabs[2]['resetSecret'] = FuncUtils.isPassAuthority(
          [PermissionConstant.mineUserManageOwnerResetSecret]);
      allTabs[2]['disable'] = FuncUtils.isPassAuthority(
          [PermissionConstant.mineUserManageOwnerDisable]);
      result.add(allTabs[2]);
    }
    tabs.addAll(result);
    nowTab = tabs[0];
    if (nowTab['type'] == 0) {
      orgTypes = [0];
      organizationId = '';
      selectedID = '';
      orgId = '';
    } else if (nowTab['type'] == 1) {
      orgTypes = [1, 2, 3];
      organizationId = '';
      selectedID = '';
      orgId = '';
    } else if (nowTab['type'] == 2) {
      orgTypes = [3];
      organizationId = '';
      selectedID = '';
      orgId = '';
    }
    update();
  }
}
